package cn.sczc.jh.client.service.sensorHistory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.sczc.jh.client.entity.SensorHistory;
import cn.sczc.jh.client.mapper.sensorHistroy.SensorHistoryMapper;
import cn.sczc.jh.client.vo.ChartVo;
import cn.sczc.jh.client.vo.SeriesData;
import cn.sczc.jh.client.vo.XAxis;

@Service
public class SensorHistoryService {
	@Autowired
	private SensorHistoryMapper sensorHistoryMapper;

	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public List<String> getLastDate() {
		List<String> list = new ArrayList<String>();
		Date endDate = sensorHistoryMapper.selectLastDate();
		if (endDate != null) {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endDate);
			calendar.add(Calendar.DAY_OF_MONTH, -1);
			Date startDate = calendar.getTime();
			list.add(formatter.format(startDate));
			list.add(formatter.format(endDate));
		}
		return list;
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public List<SensorHistory> qryList(Map<String, Object> params) {
		List<SensorHistory> alist = sensorHistoryMapper.selectByMap(params);
		List<SensorHistory> list = sensorHistoryMapper.select(params);
		return list;
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public Page<SensorHistory> queryHistoryGasData(Page<SensorHistory> page, Map<String, Object> params) {
		List<SensorHistory> list = sensorHistoryMapper.selectByHistoryParamsByPage(page, params);
		List<SensorHistory> resultList = new ArrayList<SensorHistory>();
		if (list != null && list.size() > 0) {
			for (SensorHistory vo : list) {
				SensorHistory sh = new SensorHistory();
				Map maps = (Map) JSON.parse(vo.getProperties());
				sh.setOid(vo.getOid());
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String dateString = formatter.format(vo.getCreateTime());
				sh.setTimeString(dateString);
				sh.setEquNo(vo.getEquNo());
				if (vo.getSensorAddress().length() == 1) {
					sh.setSensorAddress("00" + vo.getSensorAddress());
				} else {
					sh.setSensorAddress("0" + vo.getSensorAddress());
				}
				sh.setGasName(maps.get("gasName").toString());
				sh.setBatteryVoltage(maps.get("batteryVoltage").toString());
				sh.setGasConcentration(maps.get("gasConcentration").toString());
				sh.setMeasurementUnit(maps.get("measurementUnit").toString());
				StringBuffer s = new StringBuffer();

				int state = 0;// 0正常，1红色，2黄色，3灰色

				if (maps.get("workState") != null) {
					String workState = maps.get("workState").toString();
					if ("Normal".equals(workState)) {
						s.append("正常、");
					} else if ("Close".equals(workState)) {
						s.append("关闭、");
						state = 3;
					} else if ("NotFond".equals(workState)) {
						s.append("未找到、");
						state = 3;
					} else if ("Disappear".equals(workState)) {
						s.append("失踪、");
						state = 3;
					}
				}
				if (Boolean.parseBoolean((maps.get("isBatteryUnderVoltage")).toString())) {
					s.append("电池欠压（" + maps.get("batteryVoltage").toString() + "）、");
					state = 2;
				}
				if (Boolean.parseBoolean((maps.get("isLowAlarm")).toString())) {
					s.append("低报、");
					state = 1;
				}
				if (Boolean.parseBoolean((maps.get("isHighAlarm")).toString())) {
					s.append("高报、");
					state = 1;
				}
				if (Boolean.parseBoolean((maps.get("isModelException")).toString())) {
					s.append("模块异常、");
					state = 1;
				}
				if (s.length() > 0) {
					s.deleteCharAt(s.length() - 1);
				}
				sh.setDesc(s.toString());
				sh.setState(state);
				resultList.add(sh);
			}
		}
		page.setRecords(resultList);
		return page;
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public ChartVo queryHistoryGasChart(Map<String, Object> params) {
		ChartVo vo = new ChartVo();
		vo.setTitle("气体数据折线图：" + params.get("deviceSerial"));
		if (params.get("deviceSerial") != null && !"".equals(params.get("deviceSerial").toString())) {
			String code = params.get("deviceSerial").toString();
			params.put("deviceSerial", Integer.valueOf(code).intValue());
		}
		List<SensorHistory> dataList = sensorHistoryMapper.selectByHistoryParams(params);
		if (dataList != null && dataList.size() > 0) {
			List<String> gasIdList = new ArrayList<String>();
			List<String> xAxisData = new ArrayList<String>();
			List<String> legendData = new ArrayList<String>();
			List<SensorHistory> gtList = new ArrayList<SensorHistory>();
			for (SensorHistory dataVo : dataList) {
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String dateString = formatter.format(dataVo.getCreateTime());
				xAxisData.add(dateString);
				Map maps = (Map) JSON.parse(dataVo.getProperties());
				if (!gasIdList.contains(dataVo.getSensorAddress())) {
					SensorHistory sh = new SensorHistory();
					gasIdList.add(dataVo.getSensorAddress());
					legendData.add(maps.get("gasName").toString());
					sh.setSensorAddress(dataVo.getSensorAddress());
					sh.setGasName(maps.get("gasName").toString());
					gtList.add(sh);
				}
			}
			vo.setLegendData(legendData);
			XAxis xAxis = new XAxis();
			xAxis.setData(xAxisData);
			vo.setxAxis(xAxis);
			List<SeriesData> sdList = new ArrayList<SeriesData>();
			for (int i = 0; i < gtList.size(); i++) {
				SeriesData sd = new SeriesData();
				sd.setName(gtList.get(i).getGasName());
				sd.setStack("总量");
				sd.setType("line");
				List<String> sdataList = new ArrayList<String>();
				for (SensorHistory dataVo : dataList) {
					Map maps = (Map) JSON.parse(dataVo.getProperties());
					Boolean isHaveGas = false;
					if (dataVo.getSensorAddress().equals(gtList.get(i).getSensorAddress())) {
						isHaveGas = true;
						sdataList.add(maps.get("gasConcentration").toString());
					}
					if (!isHaveGas) {
						sdataList.add("");
					}
				}
				sd.setData(sdataList);
				sdList.add(sd);
			}
			vo.setSeriesData(sdList);
		} else {
			XAxis xAxis = new XAxis();
			xAxis.setData(new ArrayList<String>());
			vo.setxAxis(xAxis);
		}
		return vo;
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public List<SensorHistory> queryHistoryGasDataNoPage(Map<String, Object> params) {
		List<SensorHistory> list = sensorHistoryMapper.selectByHistoryParams(params);
		List<SensorHistory> resultList = new ArrayList<SensorHistory>();
		if (list != null && list.size() > 0) {
			for (SensorHistory vo : list) {
				SensorHistory sh = new SensorHistory();
				Map maps = (Map) JSON.parse(vo.getProperties());
				sh.setOid(vo.getOid());
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String dateString = formatter.format(vo.getCreateTime());
				sh.setTimeString(dateString);
				;
				sh.setEquNo(vo.getEquNo());
				if (vo.getSensorAddress().length() == 1) {
					sh.setSensorAddress("00" + vo.getSensorAddress());
				} else {
					sh.setSensorAddress("0" + vo.getSensorAddress());
				}
				sh.setGasName(maps.get("gasName").toString());
				sh.setBatteryVoltage(maps.get("batteryVoltage").toString());
				sh.setGasConcentration(maps.get("gasConcentration").toString());
				sh.setMeasurementUnit(maps.get("measurementUnit").toString());
				StringBuffer s = new StringBuffer();
				if (maps.get("workState") != null) {
					String workState = maps.get("workState").toString();
					if ("Normal".equals(workState)) {
						s.append("正常、");
					} else if ("Close".equals(workState)) {
						s.append("关闭、");
					} else if ("NotFond".equals(workState)) {
						s.append("未找到、");
					} else if ("Disappear".equals(workState)) {
						s.append("失踪、");
					}
				}
				if (Boolean.parseBoolean((maps.get("isBatteryUnderVoltage")).toString())) {
					s.append("电池欠压（" + maps.get("batteryVoltage").toString() + "）、");
				}
				if (Boolean.parseBoolean((maps.get("isLowAlarm")).toString())) {
					s.append("低报、");
				}
				if (Boolean.parseBoolean((maps.get("isHighAlarm")).toString())) {
					s.append("高报、");
				}
				if (Boolean.parseBoolean((maps.get("isModelException")).toString())) {
					s.append("模块异常、");
				}
				if (s.length() > 0) {
					s.deleteCharAt(s.length() - 1);
				}
				sh.setDesc(s.toString());
				resultList.add(sh);
			}
		}
		return resultList;
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public List<String> selectSensorAddressList() {
		List<String> list = sensorHistoryMapper.selectSensorAddressList();
		List<String> resultList = new ArrayList<String>();
		if (list != null && list.size() > 0) {
			for (String code : list) {
				if (code.length() == 1) {
					resultList.add("00" + code);
				} else {
					resultList.add("0" + code);
				}
			}
		}
		return resultList;
	}

}
